package cn.myjerry.thread.syn;

/**
 * 单例创建方式
 * 懒汉式
 * 1）构造器私有化，避免外部直接创建对象
 * 2）声明一个私有的静态变量
 * 3）创建一个对外的公共的静态方法访问该变量，如果变量没有对象，创建该对象
 *
 */
public class MyJvm {
	private static MyJvm instance = null;
	
	private MyJvm() {}
	
	public static MyJvm getInstance(long time) {
		if(instance == null) {
			synchronized(Jvm.class) {
				if (instance == null) {
					try {
						Thread.sleep(time);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					instance = new MyJvm();
				}
			}
		}
		return instance;
	}
}
/**
 * 饿汉式
 */
class MyJvm1 {
	private static MyJvm1 instance = new MyJvm1();
	
	private MyJvm1() {}
	
	public static MyJvm1 getInstance(long time) {
		return instance;
	}
}

class MyJvm2 {
	private static class JvmHolder {
		private static MyJvm2 instance = new MyJvm2();
	}
	
	private MyJvm2() {}
	
	public static MyJvm2 getInstance(long time) {
		return JvmHolder.instance;
	}
}
